# plugs/dig.py
#
#
#

""" dig command .. this is to show how to use popen2 in a safe way aka
    always use a list as parameter. NOTE: use whitelist to prevent options 
    being passed as arguments.
"""

__copyright__ = 'this file is in the public domain'

from gozerbot.generic import gozerpopen
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.plughelp import plughelp
import re

plughelp.add('dig', 'run a dig command')

def handle_dig(bot, ievent):
    """ dig <domain> <querytype> .. show dig response """
    if len(ievent.args) < 2:
        ievent.missing('<domain> <querytype>')
        return
    # call dig commands .. NOTE: use list as argument to popen2.popen4
    args = []
    args.append('dig')
    args.append(ievent.args[0])
    args.append(ievent.args[1])
    try:
        proces = gozerpopen(args)
    except Exception, ex:
        ievent.reply('error running popen: %s' % str(ex))
        return
    data = proces.fromchild.readlines()
    if proces.wait():
        ievent.reply('error running dig')
        return
    result = []
    doit = 0
    for i in data:
        # search output for answer section
        if i.find('ANSWER SECTION') != -1:
            doit = 1
            continue
        i = i.strip()
        if i and doit:
            i = i.replace('\t',' ')
            result.append(i)
            if i.find(';;') != -1:
                doit = 0
    if result:
        ievent.reply(' ==> '.join(result))
    else:
        ievent.reply('no result')

cmnds.add('dig', handle_dig, 'USER')
examples.add('dig', 'dig <hostname> <querytype> .. show dig output', \
'dig r8.cg.nu A')
